package com.sunwayworld.basemodule.basedata.index.io;

import com.sunwayworld.baseline.framework.override.LimsExcelHelper;
import com.sunwayworld.basemodule.basedata.index.bean.LimsIndexBean;
import com.sunwayworld.basemodule.basedata.index.service.LimsIndexService;
import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.exception.InvalidDataException;
import com.sunwayworld.framework.io.file.FilePathDTO;
import com.sunwayworld.framework.io.file.FilePathManager;
import com.sunwayworld.framework.spring.annotation.GikamBean;
import com.sunwayworld.framework.utils.BeanUtils;
import com.sunwayworld.framework.utils.CollectionUtils;
import com.sunwayworld.framework.utils.StringUtils;
import com.sunwayworld.module.item.file.bean.CoreFileBean;
import com.sunwayworld.module.item.file.bean.CoreFileImportResultDTO;
import com.sunwayworld.module.item.file.function.CoreFileImportFunction;
import com.sunwayworld.module.item.file.manager.CoreFileManager;
import com.sunwayworld.module.item.file.utils.CoreFileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName LimsIndexImportFileFunction
 * @Author gaozq
 * @Date 2023/7/12
 * @Version 1.0
 **/
@Component(value = "LimsIndexImportFileFunction")
@GikamBean
public class LimsIndexImportFileFunction implements CoreFileImportFunction {

    @Autowired
    @Lazy
    private LimsIndexService limsIndexService;

    @Override
    @Transactional
    public CoreFileImportResultDTO apply(CoreFileBean coreFileBean) {
        CoreFileImportResultDTO importResultRepresentation = new CoreFileImportResultDTO();
        FilePathDTO fr = CoreFileUtils.toFilePath(coreFileBean);

        // 从tos服务器下载
        CoreFileManager coreFileManager = ApplicationContextHelper.getBean(CoreFileManager.class);
        coreFileManager.download(coreFileBean, FilePathManager.getLocalPath(fr));

        List<LimsIndexBean> indexBeans = LimsExcelHelper.readDataFromExcel(FilePathManager.getLocalPath(fr).toString(), 0, 1, LimsIndexBean.class);
        if (CollectionUtils.isEmpty(indexBeans)) {
            throw new InvalidDataException("导入表格非法！");
        }

        List<String> columns = Arrays.asList("indexCode", "i5Index", "i7Index");
        List<String> colNames = Arrays.asList("【INDEX编码】", "【I5_INDEX序列】", "【I7_INDEX序列】");

        indexBeans.forEach(a -> {
            StringBuilder msg = new StringBuilder();
            for (int i = 0; i < columns.size(); i++) {
                Object value = BeanUtils.getPropertyValue(a, columns.get(i));
                if (value == null || (value.getClass().equals(String.class) && value.equals(""))) {
                    msg.append(colNames.get(i));
                }
            }
            if (msg.length() > 0) {
                msg.append(" 为必填项；");
            }
            if (msg.length() > 0) {
                if (!StringUtils.isBlank(a.getExt$Item("validateimpmsg"))) {
                    a.setExt$Item("validateimpmsg", a.getExt$Item("validateimpmsg").concat(msg.toString()));
                } else {
                    a.setExt$Item("validateimpmsg", msg.toString());
                }
            }
        });
        List<LimsIndexBean> exists = limsIndexService.selectAll();

        Map<String, List<LimsIndexBean>> groupByIndexCode = indexBeans.stream().filter(m -> !StringUtils.isBlank(m.getIndexCode())).collect(Collectors.groupingBy(LimsIndexBean::getIndexCode));
        groupByIndexCode.forEach((c, temp)->{
            //导入校验编码是否重复
            if(temp.size()>1){
                temp.forEach(a -> {
                    a.setExt$Item("validateimpmsg", "【INDEX编码】重复！");
                });
            }
            List<LimsIndexBean> te=exists.stream().filter(e->c.equals(e.getIndexCode())).collect(Collectors.toList());
            //校验和表里面的编码是否相同
            if(!te.isEmpty()){
                temp.forEach(a -> {
                    a.setExt$Item("validateimpmsg", "【INDEX编码】重复！");
                });
            }

        });
        // 返还校验结果
        if (indexBeans.stream().anyMatch(i -> !StringUtils.isEmpty(i.getExt$Item("validateimpmsg")))) {
            FilePathDTO filePathDTO = LimsExcelHelper.writeImportFailureListAsExcel(FilePathManager.getLocalPath(fr).toString(), indexBeans, 0, 1, "导入错误信息.xlsx", false);
            importResultRepresentation.setUrl(FilePathManager.getUrl(filePathDTO));
            importResultRepresentation.setMessage("导入失败");
            return importResultRepresentation;
        }
        indexBeans.forEach(a -> {
            a.setId(ApplicationContextHelper.getNextIdentity());
        });
        limsIndexService.getDao().insert(indexBeans);
        importResultRepresentation.setMessage("导入成功");
        return importResultRepresentation;
    }

    @Override
    public boolean test(CoreFileBean coreFile, String service) {
        return true;
    }
}
